import { Avatar, message } from "antd";
import { useParams } from "react-router-dom";
import DOMPurify from "dompurify";
import style from "./index.module.css";
import { addPostCommentApi } from "@/apis/client";
import { getPostCommentListApi } from "@/apis/comment";
import { getPostApi } from "@/apis/post";
import { useEffect, useState } from "react";
import timeAgo from "@/utils/timeAge";
import LikeButton from "@/components/like";
import CommentButton from "@/components/comment";
import { MessageOutlined, UserOutlined } from "@ant-design/icons";
import { useSelector } from "react-redux";

export default function PostInfo() {
  const { username, avatar } = useSelector((state: any) => state.user.profile);
  const { id } = useParams();
  const [post, setPost] = useState({} as any);
  const [commentList, setCommentList] = useState([]);
  const [comment, setComment] = useState("");
  const [commentCount, setCommentCount] = useState(0);

  function sanitize(html: string) {
    return DOMPurify.sanitize(html);
  }

  async function getPost() {
    try {
      const res: any = await getPostApi(id);
      if (res.code === 0) {
        setPost(res.data);
        await getPostCommentList(res.data.id);
      } else {
        message.error(res.message || "获取帖子失败");
      }
    } catch (error) {
      message.error("获取帖子失败");
    }
  }

  async function getPostCommentList(id: any) {
    try {
      const res: any = await getPostCommentListApi({ page: 1, size: 30 }, id);
      if (res.code === 0) {
        setCommentList(res.data.records);
        setCommentCount(res.data.total);
      } else {
        console.error(res.message);
      }
    } catch (error) {
      console.error(error);
    }
  }

  async function addPostComment() {
    if (!comment.trim()) {
      message.warning("评论内容不能为空");
      return;
    }
    try {
      const res: any = await addPostCommentApi({
        postId: post.id,
        commentContent: comment,
      });
      if (res.code === 0) {
        message.success("评论成功！");
        setComment("");
        getPostCommentList(post.id);
        getPost();
      }
    } catch (error) {
      console.error(error);
    }
  }

  function handleLike(liked: boolean) {
    liked ? message.success("点赞成功") : message.warning("取消点赞");
  }

  useEffect(() => {
    getPost();
  }, []);

  return (
    <div className={style["post-info-container"]}>
      <h1 className={style["post-info-title"]}>帖子详情</h1>

      {/* 作者信息 */}
      <section className={style["post-author-box"]}>
        <Avatar
          className={style["post-avatar"]}
          src={post?.avatar}
          icon={<UserOutlined />}
          onError={() => {
            return true;
          }}
        />
        <p className={style["post-username"]}>{post.username}</p>
      </section>

      {/* 帖子内容 */}
      <section className={style["post-box"]}>
        <h1 style={{ textAlign: "center" }}>{post.title}</h1>
        <p className={style["post-meta"]}>
          <span>发布时间：{post.createTime}</span>
          <span>更新时间：{post.updateTime}</span>
        </p>
        <div
          className={style["post-content"]}
          dangerouslySetInnerHTML={{ __html: sanitize(post.content) }}
        />
      </section>

      {/* 评论区 */}
      <section className={style["post-comment"]}>
        <h2 className={style["post-comment-label"]}>
          <MessageOutlined />
          评论区
          <span className={style["comment-count"]}>（{commentCount}条）</span>
        </h2>

        {/* 评论列表 */}
        <section className={style["comment-list"]}>
          {commentList.length > 0 ? (
            commentList.map((item: any) => (
              <div key={item.id} className={style["comment-item"]}>
                <div className={style["comment-author"]}>
                  <Avatar
                    className={style["comment-avatar"]}
                    src={item?.avatar}
                    icon={<UserOutlined />}
                    onError={() => {
                      return true;
                    }}
                  />
                  <span className={style["comment-username"]}>
                    {item.username}
                  </span>
                  <span className={style["comment-time"]}>
                    {timeAgo(item.commentTime)}
                  </span>
                </div>
                <p className={style["comment-content"]}>
                  {item.commentContent}
                </p>
              </div>
            ))
          ) : (
            <p className={style["no-comment"]}>暂无评论，快来发表你的看法吧~</p>
          )}
        </section>
      </section>
      <LikeButton
        initialLiked={post.isLiked}
        likeCount={post.likeCount}
        onLike={handleLike}
        postId={id}
      />
      <CommentButton
        type="post"
        commentCount={post.commentCount}
        addComment={addPostComment}
        currentUser={{
          username: username,
          avatar: avatar,
        }}
        comment={comment}
        setComment={setComment}
      />
    </div>
  );
}
